import { IPublicTypeProjectSchema } from '@alilc/lowcode-types';

const lifeCycleNames = [
  'componentDidMount',
  'componentWillUnmount',
  'componentDidUpdate',
  'componentDidCatch',
];

export const fixLifeCycleDuplicated = async (
  schema: IPublicTypeProjectSchema,
) => {
  const { componentsTree } = schema;
  for (let index = 0; index < componentsTree.length; index++) {
    const documentNode = componentsTree[index];
    if (documentNode.methods) {
      lifeCycleNames.forEach((lifeCycleName) => {
        const lifeCycle =
          documentNode.lifeCycles?.[lifeCycleName] ||
          documentNode.methods?.[lifeCycleName];
        if (documentNode?.methods?.[lifeCycleName] && lifeCycle) {
          documentNode.lifeCycles = {
            ...documentNode.lifeCycles,
            [lifeCycleName]: lifeCycle,
          };
          delete documentNode?.methods?.[lifeCycleName];
        }
        // 解决声明周期不能加async问题
        if (lifeCycle && lifeCycle.value.slice(0, 10).includes('async')) {
          documentNode.lifeCycles = {
            ...documentNode.lifeCycles,
            [lifeCycleName]: {
              type: 'JSFunction',
              value: `function componentDidMount() {\n  this.async_${lifeCycleName}()\n}`,
            },
          };
          documentNode.methods = {
            ...documentNode.methods,
            [`async_${lifeCycleName}`]: lifeCycle,
          };
        }
      });
    }
  }
  return schema;
};
